const express = require("express");
const router = express.Router();
const handle = require("../routes_handle/admin");
const { Response, CODE } = require('../utils/response');

// 登录接口
router.post("/admin/login", async (req, res, next) => {
  try {
    if (!req.body) {
      return res.status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, '请求体不能为空'));
    }
    
    const result = await handle.login(req.body);
    res.json(Response.success(result, '登录成功'));
  } catch (err) {
    next(err);
  }
});
router.post("/admin/logout", async (req, res, next) => {
  try {
    const result = {
      code: 200,
      msg: '退出成功'}
    res.json(Response.success(result));
  } catch (err) {
    next(err);
  }
});

// 获取客户列表
router.post("/customer/list", async (req, res, next) => {
  try {
    const result = await handle.getCustomerList(req.body);
    res.json(Response.success(result, '获取成功'));
  } catch (err) {
    next(err);
  }
});

// 添加客户
router.post("/customer/add", async (req, res, next) => {
  try {
    if (!req.body) {
      return res.status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, '请求体不能为空'));
    }
    
    const result = await handle.addCustomer(req.body);
    res.json(Response.success(result, '添加成功'));
  } catch (err) {
    next(err);
  }
});

// 更新客户信息
router.post("/customer/update", async (req, res, next) => {
  try {
    if (!req.body) {
      return res.status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, '请求体不能为空'));
    }
    
    await handle.updateCustomer(req.body);
    res.json(Response.success('更新成功'));
  } catch (err) {
    next(err);
  }
});

// 删除客户
router.post("/customer/delete", async (req, res, next) => {
  try {
    if (!req.body || !req.body.id) {
      return res.status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, '客户ID不能为空'));
    }
    
    await handle.deleteCustomer(req.body);
    res.json(Response.success('删除成功'));
  } catch (err) {
    next(err);
  }
});

// 修改客户状态
router.post("/customer/changeStatus", async (req, res, next) => {
  try {
    if (!req.body || req.body.id === undefined || req.body.status === undefined) {
      return res.status(CODE.BAD_REQUEST)
        .json(Response.error(CODE.BAD_REQUEST, '参数不完整'));
    }
    
    await handle.changeCustomerStatus(req.body);
    res.json(Response.success('状态修改成功'));
  } catch (err) {
    next(err);
  }
});

module.exports = router;